package com.wuhunyu.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatisplus字段配置
 *
 * @author wuhunyu
 * @version 1.0
 * @date 2021-01-12 21:09
 */
@Component
public class MyBatisPlusHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        // 创建时间为空
        if (metaObject.getValue("gmtCreate") == null) {
            this.setFieldValByName("gmtCreate", new Date(), metaObject);
        }
        // 修改时间为空
        if (metaObject.getValue("gmtModified") == null) {
            this.setFieldValByName("gmtModified", new Date(), metaObject);
        }
        // 乐观锁初值
        this.setFieldValByName("version", 1L, metaObject);
        // 逻辑删除初值
        this.setFieldValByName("deleted", 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 修改时间为空
        if (metaObject.getValue("gmtModified") == null) {
            this.setFieldValByName("gmtModified", new Date(), metaObject);
        }
    }
}
